/**
 * 获取 storage 缓存数据
 * @param {*} type 类型   local：localStorage   session：sessionStorage
 * @param {*} name 缓存数据name名
 * @returns
 */
 export const getStorage = (type: 'session' | 'local', name: string) => {
  const storageType: string = type || 'local'
  let result
  if (storageType === 'local') {
    result = localStorage.getItem(name) ? localStorage.getItem(name) : ''
  } else if (storageType === 'session') {
    result = sessionStorage.getItem(name) ? sessionStorage.getItem(name) : ''
  }
  return result
}

/**
 * 设置 storage 缓存数据
 * @param {*} type 类型   local：localStorage   session：sessionStorage
 * @param {*} name 缓存数据name名
 * @param {*} content 缓存的数据内容
 */
 export const setStorage = (type: string, name: string, content: string): void => {
  const storageType: string = type || 'local'
  let data: string = content
  if (typeof data === 'object') {
    data = JSON.stringify(content)
  }
  if (storageType === 'local') {
    localStorage.setItem(name, data)
  } else if (storageType === 'session') {
    sessionStorage.setItem(name, data)
  }
}

/**
 * 将对象转换为 urlQuery
 * @param {params} Object
 */
 export const queryString = (params: object): string => {
  return Object.entries(params)
    .filter(([, value]) => !!value)
    .reduce(
      (result, current, index) => `${result}${index ? '&' : '?'}${current[0]}=${current[1]}`,
      ''
    )
}

/**
 * 获得url参数
 * @param {string} name
 * @param {Boolean} hash
 * @returns {*}
 */
 export const getQueryString = (name: string, hash?: Boolean): any => {
  let reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i')
  let r
  if (hash) {
    if (!window.location.hash) {
      return ''
    }
    r = decodeURIComponent(window.location.hash).substr(1).match(reg)
  } else {
    r = decodeURIComponent(window.location.search).substr(1).match(reg)
  }
  if (r != null) {
    return r[2]
  }
  return null
}

/**
 * 生成随机字符串
 * @param {number} len
 * @returns
 */
 export const randomString = (len?: number) => {
  const length: number = len || 32
  const $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'    // 默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1
  const maxPos = $chars.length
  let pwd = ''
  for (let i = 0; i < length; i++) {
    pwd += $chars.charAt(Math.floor(Math.random() * maxPos))
  }
  return pwd
}

/**
 * 生成请求 traceid
 */
 export const createTraceId = () => {
  const time = Date.now() // 13位
  const str = randomString(35)
  return `${time}${str}`
}

/**
 * 数字格式化处理：千分位转换、小于 0 显示、分转元
 * @param {number} num
 * @param {boolean} isMoney 表示是否是金额，是的话需要进行分转元的转换
 * @returns {string}
 */
export const formatNumber = (num: number, isMoney?: boolean): string => {
  if (num < 0 || !num) {
    return isMoney ? '0.00' : '0';
  }
  if (isMoney) num = num / 100;
  return transformToThousand(num, isMoney);
}

/**
 * 千分位转换
 * @param {number} num
 * @returns {string}
 */
export const transformToThousand = (num: number, isMoney?: boolean): string => {
  if (num < 0 || !num) {
    return isMoney ? '0.00' : '0';
  }
  let str = isMoney ? num?.toFixed(2) : num?.toString();
  return str?.replace(/(\d{1,3})(?=(\d{3})+(?:$|\.))/g,'$1,');
}

/**
 * 将一维数组转换为二维数组
 * @param {array} arr 一维数组
 * @param {number} num 每组的元素个数
 * @returns {array}
 */
export const transformToTwoDimension = (arr: Array<any>, num: number):  Array<any> => {
  const res: Array<any> = [];
  arr.map((item: any, idx: number) => {
    const pos = Math.floor(idx / num);
    if (!res[pos]) {
      res[pos] = [];
    }
    res[pos].push(item);
  });
  return res;
}

/**
 * 根据某个 key 对数组进行去重
 * @param {array} list 待去重的数组
 * @param {number} key 需要进行去重的字段
 * @returns {array}
 */
export const removeRepeatedItems = (list: Array<any>, key: string): Array<any> => {
  const map = new Map();
  list.forEach(item=>{
    !map.has(item[key]) && map.set(item[key],item);
  });
  return [...map.values()];
}

/**
 * 数字或字符串转数字 如 '1，235' =>  1235
 * @param {String | Number} stringValue 数字或字符串
 * @returns {Number} url icon地址
 */
export const getStringNumberValue = (stringValue: String | Number) => {
  if (typeof(stringValue) === 'number') {
      return stringValue
  }
  return Number((stringValue + '').replace(/,/g,""))
}
